#include "Liberay.h"
#define DEL_NUM  0x7F   //删除的asccll码值
#define MAX_ATTEMPTS 3  // 最大尝试次数

// 初始化图书馆系统
void init_library(LibrarySystem *lib) {
    lib->book_head = NULL;              //书头
    lib->book_count = 0;
    
    lib->reader_head = NULL;            //读者头
    lib->reader_count = 0;
    
    lib->record_head = NULL;            //借阅头
    lib->record_count = 0;
}

// 添加图书到双向循环链表(尾插法)
void add_book(LibrarySystem *lib, Book book) {
    Book *new_book = (Book*)malloc(sizeof(Book));
    if (!new_book) {
        printf("内存分配失败!\n");
        return;
    }
    
    *new_book = book;
    
    if (lib->book_head == NULL) {
        new_book->prev = new_book;
        new_book->next = new_book;
        lib->book_head = new_book;
    } else {
        Book *last = lib->book_head->prev;
        
        new_book->next = lib->book_head;
        new_book->prev = last;
        
        last->next = new_book;
        lib->book_head->prev = new_book;
    }
    
    lib->book_count++;
    printf("图书添加成功!\n");
}

// 删除图书（根据编号ID删除）
void delete_book(LibrarySystem *lib, char *book_id) {
    if (lib->book_head == NULL) {
        printf("没有图书可删除!\n");
        return;
    }
    
    Book *current = lib->book_head;
    int found = 0;
    do {
        if (strcmp(current->id, book_id) == 0) {
            found = 1;
            break;
        }
        current = current->next;
    } while (current != lib->book_head);
    
    if (!found) {
        printf("未找到ID为%s的图书!\n", book_id);
        return;
    }
    
    // 检查是否有未归还的记录
    BorrowRecord *record = lib->record_head;
    if (record != NULL) {
        do {
            if (strcmp(record->book_id, book_id) == 0 && record->return_date == 0) {
                printf("不能删除，该书有未归还的记录!\n");
                return;
            }
            record = record->next;
        } while (record != lib->record_head);
    }
    
    // 更新链表指针
    if (lib->book_count == 1) {
        lib->book_head = NULL;
    } else {
        current->prev->next = current->next;
        current->next->prev = current->prev;
        
        if (current == lib->book_head) {
            lib->book_head = current->next;
        }
    }
    
    free(current);
    lib->book_count--;
    printf("图书删除成功!\n");
}

// 搜索图书
Book* search_book(LibrarySystem *lib, char *keyword) {
    if (lib->book_head == NULL) {
        printf("图书馆中没有图书!\n");
        return NULL;
    }
    
    Book *current = lib->book_head;
    Book *found = NULL;
    int count = 0;
    
    printf("\n搜索结果:\n");
    printf("----------------------------------------\n");
    
    do {
        if (strstr(current->title, keyword) != NULL || 
            strstr(current->author, keyword) != NULL || 
            strstr(current->id, keyword) != NULL ||
            strstr(current->isbn, keyword) != NULL) {
            
            print_book_info(current);
            printf("----------------------------------------\n");
            found = current;
            count++;
        }
        current = current->next;
    } while (current != lib->book_head);
    
    if (count == 0) {
        printf("未找到匹配的图书!\n");
        return NULL;
    }
    
    return found;
}

// 添加读者
void add_reader(LibrarySystem *lib, Reader reader) {
    Reader *new_reader = (Reader*)malloc(sizeof(Reader));
    if (!new_reader) {
        printf("内存分配失败!\n");
        return;
    }
    
    *new_reader = reader;
    
    if (lib->reader_head == NULL) {
        new_reader->prev = new_reader;
        new_reader->next = new_reader;
        lib->reader_head = new_reader;
    } else {
        Reader *last = lib->reader_head->prev;
        
        new_reader->next = lib->reader_head;
        new_reader->prev = last;
        
        last->next = new_reader;
        lib->reader_head->prev = new_reader;
    }
    
    lib->reader_count++;
    printf("读者添加成功!\n");
}

// 删除读者
void delete_reader(LibrarySystem *lib, char *reader_id) {
    if (lib->reader_head == NULL) {
        printf("没有读者可删除!\n");
        return;
    }
    
    Reader *current = lib->reader_head;
    int found = 0;
    
    do {
        if (strcmp(current->id, reader_id) == 0) {
            found = 1;
            break;
        }
        current = current->next;
    } while (current != lib->reader_head);
    
    if (!found) {
        printf("未找到ID为%s的读者!\n", reader_id);
        return;
    }
    
    // 检查是否有未归还的记录
    BorrowRecord *record = lib->record_head;
    if (record != NULL) {
        do {
            if (strcmp(record->reader_id, reader_id) == 0 && record->return_date == 0) {
                printf("不能删除，该读者有未归还的图书!\n");
                return;
            }
            record = record->next;
        } while (record != lib->record_head);
    }
    
    // 更新链表指针
    if (lib->reader_count == 1) {
        lib->reader_head = NULL;
    } else {
        current->prev->next = current->next;
        current->next->prev = current->prev;
        
        if (current == lib->reader_head) {
            lib->reader_head = current->next;
        }
    }
    
    free(current);
    lib->reader_count--;
    printf("读者删除成功!\n");
}

// 搜索读者
Reader* search_reader(LibrarySystem *lib, char *keyword) {
    if (lib->reader_head == NULL) {
        printf("图书馆中没有读者!\n");
        return NULL;
    }
    
    Reader *current = lib->reader_head;
    Reader *found = NULL;
    int count = 0;
    
    printf("\n搜索结果:\n");
    printf("----------------------------------------\n");
    
    do {
        if (strstr(current->name, keyword) != NULL || 
            strstr(current->id, keyword) != NULL || 
            strstr(current->phone, keyword) != NULL) {
            
            print_reader_info(current);
            printf("----------------------------------------\n");
            found = current;
            count++;
        }
        current = current->next;
    } while (current != lib->reader_head);
    
    if (count == 0) {
        printf("未找到匹配的读者!\n");
        return NULL;
    }
    
    return found;
}

// 借书
void borrow_book(LibrarySystem *lib, char *book_id, char *reader_id) {
    // 查找图书
    Book *book = NULL;
    if (lib->book_head != NULL) {
        Book *current = lib->book_head;
        do {
            if (strcmp(current->id, book_id) == 0) {
                book = current;
                break;
            }
            current = current->next;
        } while (current != lib->book_head);
    }
    
    if (book == NULL) {
        printf("未找到ID为%s的图书!\n", book_id);
        return;
    }
    
    // 检查图书状态
    if (book->available_copies <= 0) {
        printf("该书没有可借的副本!\n");
        return;
    }
    
    // 查找读者
    Reader *reader = NULL;
    if (lib->reader_head != NULL) {
        Reader *current = lib->reader_head;
        do {
            if (strcmp(current->id, reader_id) == 0) {
                reader = current;
                break;
            }
            current = current->next;
        } while (current != lib->reader_head);
    }
    
    if (reader == NULL) {
        printf("未找到ID为%s的读者!\n", reader_id);
        return;
    }
    
    // 检查读者借书量
    if (reader->current_borrow >= reader->max_borrow) {
        printf("该读者已达到最大借阅量!\n");
        return;
    }
    
    // 创建借阅记录
    BorrowRecord *new_record = (BorrowRecord*)malloc(sizeof(BorrowRecord));
    if (!new_record) {
        printf("内存分配失败!\n");
        return;
    }
    
    generate_record_id(new_record->record_id, sizeof(new_record->record_id));
    strcpy(new_record->book_id, book_id);
    strcpy(new_record->reader_id, reader_id);
    new_record->borrow_date = time(NULL);
    new_record->due_date = add_days(new_record->borrow_date, 30); // 30天后到期
    new_record->return_date = 0;
    new_record->fine = 0.0;
    
    // 添加到记录链表
    if (lib->record_head == NULL) {
        new_record->prev = new_record;
        new_record->next = new_record;
        lib->record_head = new_record;
    } else {
        BorrowRecord *last = lib->record_head->prev;
        
        new_record->next = lib->record_head;
        new_record->prev = last;
        
        last->next = new_record;
        lib->record_head->prev = new_record;
    }
    
    // 更新图书和读者信息
    book->available_copies--;
    if (book->available_copies == 0) {
        book->status = BORROWED;
    }
    
    reader->current_borrow++;
    lib->record_count++;
    
    printf("借书成功! 记录ID: %s\n", new_record->record_id);
}

// 还书
void return_book(LibrarySystem *lib, char *record_id) {
    if (lib->record_head == NULL) {
        printf("没有借阅记录!\n");
        return;
    }
    
    // 查找记录
    BorrowRecord *record = NULL;
    BorrowRecord *current = lib->record_head;
    do {
        if (strcmp(current->record_id, record_id) == 0) {
            record = current;
            break;
        }
        current = current->next;
    } while (current != lib->record_head);
    
    if (record == NULL) {
        printf("未找到ID为%s的借阅记录!\n", record_id);
        return;
    }
    
    if (record->return_date != 0) {
        printf("该记录已经归还过了!\n");
        return;
    }
    
    // 更新记录
    record->return_date = time(NULL);
    
    // 计算罚款(假设每天罚款0.5元)
    if (record->return_date > record->due_date) {
        double diff = difftime(record->return_date, record->due_date);
        int days_overdue = (int)(diff / (60 * 60 * 24));
        record->fine = days_overdue * 0.5;
    }
    
    // 查找图书
    Book *book = NULL;
    if (lib->book_head != NULL) {
        current = (BorrowRecord*)lib->book_head;
        do {
            if (strcmp(current->book_id, record->book_id) == 0) {
                book = (Book*)current;
                break;
            }
            current = current->next;
        } while (current != (BorrowRecord*)lib->book_head);
    }
    
    // 查找读者
    Reader *reader = NULL;
    if (lib->reader_head != NULL) {
        current = (BorrowRecord*)lib->reader_head;
        do {
            if (strcmp(current->book_id, record->reader_id) == 0) {
                reader = (Reader*)current;
                break;
            }
            current = current->next;
        } while (current != (BorrowRecord*)lib->reader_head);
    }
    
    // 更新图书和读者信息
    if (book) {
        book->available_copies++;
        if (book->available_copies > 0) {
            book->status = AVAILABLE;
        }
    }
    
    if (reader) {
        reader->current_borrow--;
    }
    
    printf("还书成功!\n");
    if (record->fine > 0) {
        printf("罚款金额: %.2f元\n", record->fine);
    }
}

// 保存数据到文件
// void save_to_file(LibrarySystem *lib, const char *filename) {
//     FILE *file = fopen(filename, "wb");
//     if (!file) {
//         printf("无法打开文件 %s 进行写入!\n", filename);
//         return;
//     }
    
//     // 写入图书数据
//     fwrite(&lib->book_count, sizeof(int), 1, file);
//     if (lib->book_head != NULL) {
//         Book *current = lib->book_head;
//         do {
//             fwrite(current, sizeof(Book), 1, file);
//             // 不保存指针
//             current = current->next;
//         } while (current != lib->book_head);
//     }
    
//     // 写入读者数据
//     fwrite(&lib->reader_count, sizeof(int), 1, file);
//     if (lib->reader_head != NULL) {
//         Reader *current = lib->reader_head;
//         do {
//             fwrite(current, sizeof(Reader), 1, file);
//             // 不保存指针
//             current = current->next;
//         } while (current != lib->reader_head);
//     }
    
//     // 写入记录数据
//     fwrite(&lib->record_count, sizeof(int), 1, file);
//     if (lib->record_head != NULL) {
//         BorrowRecord *current = lib->record_head;
//         do {
//             fwrite(current, sizeof(BorrowRecord), 1, file);
//             // 不保存指针
//             current = current->next;
//         } while (current != lib->record_head);
//     }
    
//     fclose(file);
//     printf("数据已保存到 %s\n", filename);
// }

// 从文件加载数据
// void load_from_file(LibrarySystem *lib, const char *filename) {
//     FILE *file = fopen(filename, "rb");
//     if (!file) {
//         printf("无法打开文件 %s 进行读取!\n", filename);
//         return;
//     }
    
//     // 清空现有数据
//     free_library(lib);
//     init_library(lib);
    
//     // 读取图书数据
//     int count;
//     fread(&count, sizeof(int), 1, file);
//     for (int i = 0; i < count; i++) {
//         Book book;
//         fread(&book, sizeof(Book), 1, file);
//         book.prev = book.next = NULL; // 重置指针
//         add_book(lib, book);
//     }
    
//     // 读取读者数据
//     fread(&count, sizeof(int), 1, file);
//     for (int i = 0; i < count; i++) {
//         Reader reader;
//         fread(&reader, sizeof(Reader), 1, file);
//         reader.prev = reader.next = NULL; // 重置指针
//         add_reader(lib, reader);
//     }
    
//     // 读取记录数据
//     fread(&count, sizeof(int), 1, file);
//     for (int i = 0; i < count; i++) {
//         BorrowRecord record;
//         fread(&record, sizeof(BorrowRecord), 1, file);
//         record.prev = record.next = NULL; // 重置指针
//         // 添加到记录链表
//         BorrowRecord *new_record = (BorrowRecord*)malloc(sizeof(BorrowRecord));
//         if (!new_record) {
//             printf("内存分配失败!\n");
//             continue;
//         }
//         *new_record = record;
        
//         if (lib->record_head == NULL) {
//             new_record->prev = new_record;
//             new_record->next = new_record;
//             lib->record_head = new_record;
//         } else {
//             BorrowRecord *last = lib->record_head->prev;
            
//             new_record->next = lib->record_head;
//             new_record->prev = last;
            
//             last->next = new_record;
//             lib->record_head->prev = new_record;
//         }
        
//         lib->record_count++;
//     }
    
//     fclose(file);
//     printf("数据已从 %s 加载\n", filename);
// }

// 释放图书馆系统内存
void free_library(LibrarySystem *lib) {
    // 释放图书链表
    if (lib->book_head != NULL) {
        Book *current = lib->book_head;
        Book *next;
        do {
            next = current->next;
            free(current);
            current = next;
        } while (current != lib->book_head);
        lib->book_head = NULL;
    }
    
    // 释放读者链表
    if (lib->reader_head != NULL) {
        Reader *current = lib->reader_head;
        Reader *next;
        do {
            next = current->next;
            free(current);
            current = next;
        } while (current != lib->reader_head);
        lib->reader_head = NULL;
    }
    
    // 释放记录链表
    if (lib->record_head != NULL) {
        BorrowRecord *current = lib->record_head;
        BorrowRecord *next;
        do {
            next = current->next;
            free(current);
            current = next;
        } while (current != lib->record_head);
        lib->record_head = NULL;
    }
    
    lib->book_count = 0;
    lib->reader_count = 0;
    lib->record_count = 0;
}

// 打印所有图书
void print_all_books(LibrarySystem *lib) {
    if (lib->book_head == NULL) {
        printf("图书馆中没有图书!\n");
        return;
    }
    
    printf("\n所有图书信息:\n");
    printf("=================================================================================================================\n");
    printf("ID      书名                作者          出版社        ISBN          年份    分类       价格      状态      数量\n");
    printf("=================================================================================================================\n");
    
    Book *current = lib->book_head;
    do {
        printf("%-8s %-20s %-12s %-12s %-14s %-8d %-8s %-8.2f %-12s %d/%d\n",
               current->id, current->title, current->author, current->publisher,
               current->isbn, current->publish_year, current->category,
               current->price, status_to_string(current->status),
               current->available_copies, current->total_copies);
        current = current->next;
    } while (current != lib->book_head);
    
    printf("=================================================================================================================\n");
    printf("总计: %d 本图书\n", lib->book_count);
}

// 打印所有读者
void print_all_readers(LibrarySystem *lib) {
    if (lib->reader_head == NULL) {
        printf("图书馆中没有读者!\n");
        return;
    }
    
    printf("\n所有读者信息:\n");
    printf("==========================================================================================\n");
    printf("ID      姓名          性别   电话         邮箱                 地址             借书量\n");
    printf("==========================================================================================\n");
    
    Reader *current = lib->reader_head;
    do {
        char reg_date[20];
        strftime(reg_date, sizeof(reg_date), "%Y-%m-%d", localtime(&current->register_date));
        
        printf("%-8s %-12s %-6s %-12s %-20s %-16s %d/%d\n",
               current->id, current->name, current->gender,
               current->phone, current->email, current->address,
               current->current_borrow, current->max_borrow);
        current = current->next;
    } while (current != lib->reader_head);
    
    printf("==========================================================================================\n");
    printf("总计: %d 位读者\n", lib->reader_count);
}

// 打印所有借阅记录
void print_all_records(LibrarySystem *lib) {
    if (lib->record_head == NULL) {
        printf("没有借阅记录!\n");
        return;
    }
    
    printf("\n所有借阅记录:\n");
    printf("========================================================================================================\n");
    printf("记录ID              图书ID   读者ID   借出日期      应还日期      归还日期      罚款\n");
    printf("========================================================================================================\n");
    
    BorrowRecord *current = lib->record_head;
    do {
        char borrow_date[20], due_date[20], return_date[20];
        strftime(borrow_date, sizeof(borrow_date), "%Y-%m-%d", localtime(&current->borrow_date));
        strftime(due_date, sizeof(due_date), "%Y-%m-%d", localtime(&current->due_date));
        
        if (current->return_date == 0) {
            strcpy(return_date, "未归还");
        } else {
            strftime(return_date, sizeof(return_date), "%Y-%m-%d", localtime(&current->return_date));
        }
        
        printf("%-20s %-8s %-8s %-12s %-12s %-12s %.2f\n",
               current->record_id, current->book_id, current->reader_id,
               borrow_date, due_date, return_date, current->fine);
        current = current->next;
    } while (current != lib->record_head);
    
    printf("========================================================================================================\n");
    printf("总计: %d 条记录\n", lib->record_count);
}

// 辅助函数: 将状态枚举转换为字符串
char* status_to_string(BookStatus status) {
    switch (status) {
        case AVAILABLE: return "可借阅";
        case BORROWED: return "已借出";
        case RESERVED: return "已预约";
        case UNDER_REPAIR: return "维修中";
        default: return "未知";
    }
}

// 辅助函数: 将字符串转换为状态枚举
BookStatus string_to_status(const char *str) {
    if (strcmp(str, "可借阅") == 0) return AVAILABLE;
    if (strcmp(str, "已借出") == 0) return BORROWED;
    if (strcmp(str, "已预约") == 0) return RESERVED;
    if (strcmp(str, "维修中") == 0) return UNDER_REPAIR;
    return AVAILABLE;
}

// 辅助函数: 打印图书信息
void print_book_info(Book *book) {
    printf("图书ID: %s\n", book->id);
    printf("书名: %s\n", book->title);
    printf("作者: %s\n", book->author);
    printf("出版社: %s\n", book->publisher);
    printf("ISBN: %s\n", book->isbn);
    printf("出版年份: %d\n", book->publish_year);
    printf("分类: %s\n", book->category);
    printf("价格: %.2f\n", book->price);
    printf("状态: %s\n", status_to_string(book->status));
    printf("数量: %d/%d\n", book->available_copies, book->total_copies);
}

// 辅助函数: 打印读者信息
void print_reader_info(Reader *reader) {
    char reg_date[20];
    strftime(reg_date, sizeof(reg_date), "%Y-%m-%d", localtime(&reader->register_date));
    
    printf("读者ID: %s\n", reader->id);
    printf("姓名: %s\n", reader->name);
    printf("性别: %s\n", reader->gender);
    printf("电话: %s\n", reader->phone);
    printf("邮箱: %s\n", reader->email);
    printf("地址: %s\n", reader->address);
    printf("注册日期: %s\n", reg_date);
    printf("借书量: %d/%d\n", reader->current_borrow, reader->max_borrow);
}

// 辅助函数: 打印记录信息
void print_record_info(BorrowRecord *record) {
    char borrow_date[20], due_date[20], return_date[20];
    strftime(borrow_date, sizeof(borrow_date), "%Y-%m-%d", localtime(&record->borrow_date));
    strftime(due_date, sizeof(due_date), "%Y-%m-%d", localtime(&record->due_date));
    
    if (record->return_date == 0) {
        strcpy(return_date, "未归还");
    } else {
        strftime(return_date, sizeof(return_date), "%Y-%m-%d", localtime(&record->return_date));
    }
    
    printf("记录ID: %s\n", record->record_id);
    printf("图书ID: %s\n", record->book_id);
    printf("读者ID: %s\n", record->reader_id);
    printf("借出日期: %s\n", borrow_date);
    printf("应还日期: %s\n", due_date);
    printf("归还日期: %s\n", return_date);
    printf("罚款: %.2f\n", record->fine);
}

// 辅助函数: 去除字符串两端的空白字符
void trim_string(char *str) {
    char *end;
    
    // 去除前导空白
    while (isspace((unsigned char)*str)) str++;
    
    if (*str == 0) return;
    
    // 去除尾部空白
    end = str + strlen(str) - 1;
    while (end > str && isspace((unsigned char)*end)) end--;
    
    // 写入新的空字符
    *(end + 1) = 0;
}

// 辅助函数: 在日期上添加天数
time_t add_days(time_t date, int days) {
    return date + days * 24 * 60 * 60;
}

// 辅助函数: 生成记录ID
void generate_record_id(char *buffer, size_t size) {
    time_t now = time(NULL);
    struct tm *tm = localtime(&now);
    
    snprintf(buffer, size, "REC-%04d%02d%02d-%06ld",
             tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
             (long)(now % 1000000));
}
bool Password()
{
    char mima[10] = "123456";
    int attempts = 0;
    
    while (attempts < MAX_ATTEMPTS) {
        system("stty -icanon");  // 设置一次性读完操作
        system("stty -echo");    // 关闭回显
        
        char passwd[10] = {0};
        int ch;
        int lp = 0;

        printf("请输入密码:");

        while (lp < sizeof(passwd) - 1)  // 保留一个位置给 '\0'
        {
            ch = getchar();
            
            if (ch == '\n') {
                passwd[lp] = '\0';
                break;
            }
            else if (ch == DEL_NUM) {
                if (lp > 0) {
                    lp--;
                    printf("\b \b");  // 退格并清除星号
                }
            }
            else {
                passwd[lp++] = ch;
                printf("*");
            }
        }
        
        system("stty echo");      // 恢复回显
        system("stty icanon");    // 恢复规范模式
        printf("\n");
        
        if (strcmp(passwd, mima) == 0) //不能直接比较，否则比较的是两者的地址
        {
            return true;  // 密码正确
        } else {
            attempts++;
            if (attempts < MAX_ATTEMPTS) {
                printf("密码错误，请重新输入！\n");
            } else {
                printf("错误次数过多，请稍后再试！\n");
            }
        }
    }
    
    return false;  // 密码错误
}

// 主菜单
void display_menu() {
    printf("\n===== 图书管理系统 =====\n");
    printf("1. 添加图书\n");
    printf("2. 删除图书\n");
    printf("3. 搜索图书\n");
    printf("4. 显示所有图书\n");
    printf("5. 添加读者\n");
    printf("6. 删除读者\n");
    printf("7. 搜索读者\n");
    printf("8. 显示所有读者\n");
    printf("9. 借书\n");
    printf("10. 还书\n");
    printf("11. 显示所有借阅记录\n");
    // printf("12. 保存数据到文件\n");
    // printf("13. 从文件加载数据\n");
    printf("0. 退出\n");
    printf("========================\n");
    printf("请选择操作: ");
}


